package com.wyl.studyredis.business.controller;


import cn.hutool.core.util.StrUtil;
import com.wyl.studyredis.business.dto.SchoolAddDto;
import com.wyl.studyredis.business.dto.SchoolUpdateDto;
import com.wyl.studyredis.business.entity.School;
import com.wyl.studyredis.business.service.ISchoolService;
import com.wyl.studyredis.business.vo.SchoolVo;
import com.wyl.studyredis.framework.ResponseVo;
import com.wyl.studyredis.framework.util._BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 *
 * @author wyl
 * @since 2022-02-11
 */
@RestController
@RequestMapping("/school")
public class SchoolController {

    @Autowired
    private ISchoolService schoolService;

    @GetMapping("/list")
    public ResponseVo<List<School>> list() {
        List<School> list = schoolService.list();
        return ResponseVo.success(list);
    }

    @GetMapping("/get")
    public ResponseVo<SchoolVo> get(@RequestParam("id") String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseVo.fail("主键不能为空");
        }
        try {
            SchoolVo vo = schoolService.getSchoolVoByIdInCache(id, true);
            return ResponseVo.success(vo);
        } catch (Exception e) {
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/add")
    public ResponseVo<String> add(@RequestBody @Valid SchoolAddDto dto) {
        try {
            School school = _BeanUtil.copyProperties(dto, School.class);
            schoolService.saveAndCache(school);
            return ResponseVo.success(school.getId());
        } catch (Exception e) {
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/update")
    public ResponseVo<String> update(@RequestBody @Valid SchoolUpdateDto dto) {
        try {
            School school = _BeanUtil.copyProperties(dto, School.class);
            schoolService.updateByIdAndCache(school);
            return ResponseVo.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseVo.error(e.getMessage());
        }
    }

    @PostMapping("/delete")
    public ResponseVo delete(@RequestParam("id") String id){
        if (StrUtil.isBlank(id)) {
            return ResponseVo.fail("主键不能为空");
        }
        schoolService.removeByIdAndCache(id);
        return ResponseVo.success();
    }


}

